const express = require('express');
const router = express.Router();
const pool = require('../db');
const axios = require('axios');
const util = require('util');
const cozeToken = require('../modules/cozeToken');

const WORKFLOW_ID = '7490477698080620598';
const BATCH_SIZE = 1; // 每次处理的记录数量

// 将 pool.query 转换为 Promise
const query = util.promisify(pool.query).bind(pool);

// 根据ID查询壁纸详情（包含上一个和下一个）
router.get('/detail/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const { tags } = req.query; // 可选的标签参数

    // 构建标签过滤条件
    let tagCondition = '';
    let queryParams = [];
    if (tags) {
      const tagList = tags.split(',').filter(tag => tag.trim());
      if (tagList.length > 0) {
        const tagConditions = tagList.map(() => 'tags LIKE ?').join(' OR ');
        tagCondition = ` AND (${tagConditions})`;
        queryParams = tagList.map(tag => `%${tag.trim()}%`);
      }
    }

    // 查询当前壁纸
    const currentQuery = `
      SELECT * FROM wallpaper_resources 
      WHERE id = ?${tagCondition}
    `;
    const currentResult = await query(currentQuery, [id, ...queryParams]);

    if (!currentResult || currentResult.length === 0) {
      return res.status(404).json({
        success: false,
        code: 404,
        message: '未找到该壁纸',
        data: null
      });
    }

    // 查询上一个壁纸（ID 大于当前 ID）
    const prevQuery = `
      SELECT * FROM wallpaper_resources 
      WHERE id > ?${tagCondition}
      ORDER BY CRC32(CONCAT(id, CURDATE()))
      LIMIT 1
    `;
    const prevResult = await query(prevQuery, [id, ...queryParams]);

    // 如果上一个壁纸没找到，则获取最后一张壁纸
    let prevWallpaper = prevResult[0];
    if (!prevWallpaper) {
      const lastQuery = `
        SELECT * FROM wallpaper_resources 
        WHERE 1=1${tagCondition}
        ORDER BY id ASC
        LIMIT 1
      `;
      const lastResult = await query(lastQuery, queryParams);
      prevWallpaper = lastResult[0];
    }

    // 查询下一个壁纸（ID 小于当前 ID）
    const nextQuery = `
      SELECT * FROM wallpaper_resources 
      WHERE id < ?${tagCondition}
      ORDER BY CRC32(CONCAT(id, CURDATE())) 
      LIMIT 1
    `;
    const nextResult = await query(nextQuery, [id, ...queryParams]);

    // 如果下一个壁纸没找到，则获取第一张壁纸
    let nextWallpaper = nextResult[0];
    if (!nextWallpaper) {
      const firstQuery = `
        SELECT * FROM wallpaper_resources 
        WHERE 1=1${tagCondition}
        ORDER BY id DESC
        LIMIT 1
      `;
      const firstResult = await query(firstQuery, queryParams);
      nextWallpaper = firstResult[0];
    }

    // 返回结果
    res.json({
      success: true,
      code: 200,
      message: '查询成功',
      data: {
        current: currentResult[0],
        prev: prevWallpaper,
        next: nextWallpaper
      }
    });
  } catch (error) {
    console.error('查询壁纸详情时出错:', error);
    res.status(500).json({
      success: false,
      code: 500,
      message: '服务器内部错误',
      error: error.message
    });
  }
});

// 增加下载量
router.post('/download/:id', async (req, res) => {
  try {
    const { id } = req.params;

    // 检查壁纸是否存在
    const records = await query(
      'SELECT id FROM wallpaper_resources WHERE id = ?',
      [id]
    );

    if (!records || records.length === 0) {
      return res.status(404).json({
        success: false,
        code: 404,
        message: '未找到该壁纸',
        data: null
      });
    }

    // 更新下载量
    await query(
      'UPDATE wallpaper_resources SET download_num = COALESCE(download_num, 0) + 1 WHERE id = ?',
      [id]
    );

    // 获取更新后的下载量
    const updatedRecord = await query(
      'SELECT download_num FROM wallpaper_resources WHERE id = ?',
      [id]
    );

    res.json({
      success: true,
      code: 200,
      message: '下载量更新成功',
      data: {
        id: parseInt(id),
        download_num: updatedRecord[0].download_num
      }
    });
  } catch (error) {
    console.error('更新下载量时出错:', error);
    res.status(500).json({
      success: false,
      code: 500,
      message: '服务器内部错误',
      error: error.message
    });
  }
});

// 分页查询壁纸资源
router.get('/list', async (req, res) => {
  try {
    const {
      page = 1,
      pageSize = 10,
      tags = ''  // 标签，多个用逗号分隔，如 "风景,动漫,人物"
    } = req.query;

    // 转换为数字类型
    const currentPage = parseInt(page);
    const limit = parseInt(pageSize);
    const offset = (currentPage - 1) * limit;

    // 构建查询条件
    let whereClause = '1 = 1';
    let queryParams = [];

    // 处理标签筛选
    if (tags) {
      const tagList = tags.split(',').filter(tag => tag.trim());
      if (tagList.length > 0) {
        const tagConditions = tagList.map(() => 'tags LIKE ?').join(' OR ');
        whereClause += ` AND (${tagConditions})`;
        queryParams.push(...tagList.map(tag => `%${tag.trim()}%`));
      }
    }

    // 查询总数
    const totalResult = await query(
      `SELECT COUNT(*) as total FROM wallpaper_resources WHERE ${whereClause}`,
      queryParams
    );
    const total = totalResult[0].total;

    // 查询数据（使用 CRC32 哈希每日变化的排序规则）
    const records = await query(
      `SELECT * FROM wallpaper_resources WHERE ${whereClause} 
       ORDER BY CRC32(CONCAT(id, CURDATE())) LIMIT ? OFFSET ?`,
      [...queryParams, limit, offset]
    );

    res.json({
      success: true,
      code: 200,
      message: '查询成功',
      data: {
        list: records,
        pagination: {
          current: currentPage,
          pageSize: limit,
          total
        }
      }
    });
  } catch (error) {
    console.error('查询壁纸资源时出错:', error);
    res.status(500).json({
      success: false,
      code: 500,
      message: '服务器内部错误',
      error: error.message
    });
  }
});

// 更新壁纸资源标签
router.post('/update-tags', async (req, res) => {
  try {
    // 1. 查询 tags 为空的记录，限制10条
    const records = await query(
      'SELECT id, image_url FROM wallpaper_resources WHERE tags IS NULL LIMIT ?',
      [BATCH_SIZE]
    );

    if (!records || records.length === 0) {
      return res.json({
        success: true,
        code: 200,
        message: '没有需要更新的记录',
        data: []
      });
    }

    const results = [];
    
    // 2. 遍历记录，调用 Coze 工作流
    for (const record of records) {
      try {
        console.log('处理记录:', record); // 添加日志

        // 获取最新的认证头
        const headers = await cozeToken.getAuthHeaders();

        // 调用 Coze 工作流
        const response = await axios.post(
          'https://api.coze.cn/v1/workflow/run',
          {
            workflow_id: WORKFLOW_ID,
            parameters: {
              input: record.image_url
            }
          },
          {
            headers: headers
          }
        );

        console.log('Coze API 响应:', response.data); // 添加日志

        // 3. 更新数据库中的 tags 字段
        // 解析 JSON 字符串为对象
        const responseData = typeof response.data.data === 'string' 
          ? JSON.parse(response.data.data) 
          : response.data.data;
        
        // 获取 output 字段
        const tagsData = responseData?.output || '';
        
        console.log('要写入的标签数据:', tagsData);
        
        // 更新数据库
        const updateResult = await query(
          'UPDATE wallpaper_resources SET tags = ? WHERE id = ?',
          [tagsData, record.id]
        );
        
        console.log('数据库更新结果:', updateResult);

        results.push({
          id: record.id,
          image_url: record.image_url,
          tags: tagsData,
          status: 'success'
        });
      } catch (error) {
        console.error(`处理记录 ${record.id} 时出错:`, error);
        results.push({
          id: record.id,
          image_url: record.image_url,
          status: 'error',
          error: error.message
        });
      }
    }

    res.json({
      success: true,
      code: 200,
      message: `成功处理 ${results.length} 条记录`,
      data: results
    });
  } catch (error) {
    console.error('更新壁纸资源标签时出错:', error);
    res.status(500).json({
      success: false,
      code: 500,
      message: '服务器内部错误',
      error: error.message
    });
  }
});

module.exports = router; 